/**
 * 基础方法
 * 1、加载菜单
 * 2、配置核对版本信息
 * 3、检测账号
 */
define([ '../common/service', '../plugins/dialog'],function( http){
    var baseFn = {
        /*
        *   初始化方法
        * */
        init: function(callback){
            var _this = this;
            _this.setVersion(function(){
                _this.setUserInfo(function(){
                    _this.initMessage();
                    _this.setMenu(callback);
                });
            });
        }
        /*
        * 存储当前fb版本号
        * */
        ,fbVersion:undefined
        /*
        *   存储当前账号的角色
        * */
        ,roleId:undefined
        /*
        * 配置版本信息
        * */
        ,setVersion: function(callback){
            var _this = this;
            $.getJSON(cors_config.api_host + '/sysmonitor/webVersion', function (json) {
                var _version = json.version || '';
                if (!_version) {
                    _version = '';
                }

                $('#now-version').html(I18N.getText('index','currentVersion') + _version);
                cors_config.basePath = _version;
       //         console.log(cors_config.basePath)
                window.localStorage.setItem('fbversion', _version);
                _this.fbVersion = _version;
                typeof(callback) == 'function' ? callback() : '';
            });
        }
        /*
        * 检测账号信息
        * */
        ,checkAccount: function(){
            var _this = this;
            // 添加如果有没有绑定账号,则跳转到绑定账号的页面
            $.ajax( {
                type : "POST",
                url : cors_config.api_host+'/entrustaccounts/businessManagers',
                xhrFields: {
                    withCredentials: true
                },
                success : function(res, textStatus, xmLHttpRequest){
                    var gotoAccount = false;
                    if(res.flag == 'success'){
                        var data = res.data;  //数据格式变更，为保证原代码不变做重新赋值处理
                        if (!data.businessmanagers || data.businessmanagers.length == 0) {
                            gotoAccount = true;
                        }
                    }else{
                        gotoAccount = true;
                    }
                    if(gotoAccount){
                        window.location.hash.indexOf('account') != -1 ? '' : window.location.hash = '#!account';
                    }
                    typeof(callback) == 'function' ? callback() : '';
                }
            });
        }
        ,userdata: undefined
        /*
        * 获取用户信息
        * */
        ,getUserInfo: function(callback){
            var _this = this;
            $.ajax( {
                type : "POST",
                url : cors_config.api_host+'/user/current',
                xhrFields: {
                    withCredentials: true
                },
                success : function(res, textStatus, xmLHttpRequest){
                    // 添加body内容
                    if(!res || typeof(res) == 'string' || res.flag == 'fail'){
                        window.location.href = 'login.html?gotoUrl='+ window.location.href;
                        return false;
                    }
                    //配置列表全局常量 i18n使用语言
                    listManagerConfig['i18n'] = res.data.language || 'zh-cn'
                    //重置用户设置、密码修改、注销所需href
                    _this.userdata = res.data;  //数据格式变更，为保证原代码不变做重新赋值处理
                    typeof callback == 'function' ? callback(_this.userdata) : '';
                }
            });
        }
        /*
        *   设置用户信息
        * */
        ,setUserInfo: function(callback){
            var _this = this;
            var data = _this.userdata;
            if(_this.userdata == undefined){
                _this.getUserInfo(function(){
                    seavuserInfo();
                });
            }else{
                seavuserInfo();
            }
            function seavuserInfo(){
                //存储账号角色
                _this.roleId = data.roleId;
                window.sessionStorage.roleId = data.roleId;
                //存储用户使用语言
                window.localStorage.language = data.language || '';
                //格式化时区
                window.sessionStorage.timezoneName = data.timezoneName || '零时区';
                window.sessionStorage.timezoneId = data.timezoneId || 'GMT';
                var _time = window.sessionStorage.timezoneId.substr(3) || '0';
                var _h = parseInt(_time);
                var _m = Math.abs(Number(_time) % 1 * 60);
                var _timeFarmat = moment(_h + ':' + _m, 'HH:mm').format('HH:mm');
                _timeFarmat = _h >= 0 ? '+' + _timeFarmat : '-' + _timeFarmat;
                window.sessionStorage.timezoneValue = _timeFarmat;
                //显示当前用户名称
                window.sessionStorage.username = data.username || '';;
                $('.user-warp .user-name').text(window.sessionStorage.username);

                // 添加如果有没有绑定账号,则跳转到绑定账号的页面
                if (data.roleId && data.roleId.indexOf(3) == -1 && data.roleId.indexOf(6) == -1) { //3 美宣,不进行验证
                    _this.checkAccount();
                }
                // 美宣、外部美宣不显示 用户中心-解决绑定
                if (!data.roleId || data.roleId.indexOf(3) != -1 || data.roleId.indexOf(6) != -1) {
                    $('#layout-header .unbind').parent().remove();
                }
                //公司信息
                window.sessionStorage.orgId = data.orgId || '';
                window.setTimeout(function(){
                    _this.openWebSocket(data.ticket);
                },3000);
                callback();
            }
        }
        /*
        * 配置菜单
        * */
        ,setMenu: function(callback){
            var _this = this;
            var fbmenu = window.localStorage.getItem('fbmenu'),
                menuObj = undefined;
            try{
                menuObj = JSON.parse(fbmenu);
            }catch(e){
                menuObj = undefined;
            };
            var navBar = $('#navBar'); //菜单项所在容器
            var fbversion = _this.fbVersion,
                roleId    = _this.roleId;
            //直接进行 menu 的渲染
            if (fbmenu && menuObj && menuObj.fbversion == fbversion && menuObj.roleId == _this.roleId) {
                console.info('setMenu:', '使用本地菜单数据进行menu渲染');
                navBar.html(_this.createMenuHtml(menuObj.data));
                typeof callback == 'function' ? callback() : '';
            //请求 menu 菜单
            } else{
                console.info('setMenu:', '请求 menu数据')
                $.ajax({
                    type : "POST",
                    url : cors_config.api_host+'/user/getMenu',
                    xhrFields: {
                        withCredentials: true
                    },
                    success : function(res, textStatus, xmLHttpRequest){
                        if(res.flag=="success"){
                            menuObj = {
                                data: res.data,
                                fbversion:fbversion,
                                roleId:roleId
                            }
                            window.localStorage.setItem('fbmenu',JSON.stringify(menuObj));
                            navBar.html(_this.createMenuHtml(res.data));
                            typeof callback == 'function' ? callback() : '';
                        }
                    }
                });
            };
            //点击菜单后清除缓存数据
            $('#navBar li a[href!="#!"]').unbind('click').bind('click', function(){
                window.sessionStorage.clear();
            });
        }
        /*
        * 生成菜单所需html
        * */
        ,createMenuHtml: function(data){
            var _this = this;
            var tmpHtml = '';
            var webversion = _this.fbVersion;
            if(!webversion){
                webversion='';
            }
            webversion = '';  //暂时移除版本控制
            $.each(data, function (i, v) {
                tmpHtml += '<li class="open">' + '<a href="' + (v.url == '#!home' ? v.url : 'javascript:;') + '">'
                        + '<i class="' + v.icon + '"></i>'
                        + '<span class="menu-item-parent">'
                        + v.value + '</span>' + '</a>';
                if (v.son && v.son.length != 0) {
                    tmpHtml += '<ul style="overflow: hidden; display: block;">'
                    $.each(v.son, function (i2, v2) {
                        if(v2.url.indexOf('http')==0){//以http开头的,代表外部窗口
                            tmpHtml += '<li><a target="_blank" href="' +  v2.url + '">' + v2.value + '</a></li>'
                        }else{
                            tmpHtml += '<li><a href="' +  v2.url + '" >' + v2.value + '</a></li>';
                        }
                    });
                    tmpHtml += '</ul>';
                }
                tmpHtml += '</li>'
            });
            return tmpHtml;
        }
        /*
        * 配置消息中心数据
        * */
        ,initMessage : function () {
            var _this = this;
            //注册点击事件
            $("#activity").bind("click", function () {
                if (!$("#activity").data("flag")) {
                    $("#activity").data("flag", true);
                    var num = $('#message-num').data("num");
                    $('#message-num').text(num);
                }
            });
            $(".mess-list").click(function () {
                $('.bell-dropdown').removeClass('active');
                window.location.hash =  "#!notice" ;
            });
            $.ajax( {
                type : "POST",
                url : cors_config.api_host+'/notice/getMessages',
                data: {param:'{}'},
                xhrFields: {
                    withCredentials: true
                },
                success : function(data, textStatus, xmLHttpRequest){
                    if(!data || data.flag == 'fail'){
                        console.log('getMessages:获取数据失败');
                        return false;
                    }

                    var data = data.data;  //数据格式变更，为保证原代码不变做重新赋值处理
                    _this.handleData(data);
                }
            });
        }
        ,handleMessage: function(res){
            var _this = this;
            var str = "";
            var lastTime = 0;
            var befStr, afterStr = "";
            var subNum = 80;   //显示的message body字数
            $(".bell-warp").find(".list-group ul").html('');
            $.each(res.resultList, function (n, obj) {
                if (n == 0) {
                    lastTime = obj.sendTime;
                }
                str += '<li class="list-group-item" id="' + obj.id + '"><span class="badge"><i class="fa fa-times"></i></span>';
                if (obj.needFunctionJump) {
                    str += '<span class="glyphicon glyphicon-exclamation-sign  mess-i"></span>';
                } else {
                    str += '<span class="glyphicon glyphicon-envelope mess-i"></span>';
                }
                if (obj.url == "" || typeof obj.url == "undefined") {
                    str += '<h4 class="mess-head">' + obj.title + '</h4>';
                } else {
                    //临时处理URL问题，之后需要进行数据库清理
                    obj.url == '/face2/adList.html' ? obj.url = '#!adList' : '';  //广告列表的
                    var url = window.location.href.replace(/face2\/\S+/i, '#!'+obj.url);
                    str += '<h4 class="mess-head">' + obj.title + '</h4>';
                }
                //加入。。。
                /*
                 if (obj.body.length > subNum) {
                 befStr = obj.body.substr(0, subNum);
                 afterStr = obj.body.substr(subNum, obj.body.length);
                 str += '<p class="mess-body">' + befStr + '...</p>';
                 str += '<span class="mess-open">[展开全文]</span>';
                 } else {
                 */
                var idpart = obj.url.split("?")[1];
                var redir = obj.url.split("?")[0];
                var imageBathId = (idpart)?idpart.match(/imageBathId=([a-z0-9]+)/i)[1]:'';
                if(!obj.url){
                    str +='<p class="mess-body" objid='+obj.id+'>'+obj.body+'</p>';
                }else{
                    if(imageBathId){

                        str += '<p class="mess-body">\
                                    <span data-toggle="modal" class="mess-head-a" imageBathId='+ imageBathId+' href='+obj.url+' objid='+obj.id+' jump='+redir+'>' + obj.body + '</span></p>';
                    }
                    else if(obj.url = '#!adList'){
                        str += '<p class="mess-body">\
                                <span href='+obj.url+' class="mess-head-a">' + obj.body + '</span></p>';
                    }else{
                        str += '<p class="mess-body">\
                                <span data-toggle="modal" data-target="#messageModal" class="mess-head-a" href='+obj.url+' objid='+obj.id+' jump='+redir+'>' + obj.body + '</span></p>';
                    }
                }
                str += '<span class="mess-open" open-status="false">[展开全文]</span>';
                //    }
                str += '<span class="mess-send-time">' + moment(obj.sendTime).format("YYYY-MM-DD HH:mm:ss") + '</span></li>';
            });
            $(".bell-warp").find(".list-group ul").prepend(str);
            $.each($('.mess-body'), function(i, v){
                if($(this).height() >= $('.mess-head-a', this).height()){
                    $('.mess-open', $(this).closest('.list-group-item')).hide();
                }
            });
            //提醒内容跳转事件

            $('.bell-warp .list-group .mess-head-a').unbind("click").click(function(e){
                e.stopPropagation();
                var imageBathId = this.getAttribute('imageBathId'),
                    href = this.getAttribute('href'),
                    oid = this.getAttribute('objid');
                if(imageBathId){
                    //初始化弹出框页面
                    http.do("/adresource/getAdimagesAllListMonByimageBathId",
                        {
                            param:JSON.stringify({'imageBathId':imageBathId})
                        }).then(function(result){
                        _this.initMessageModal(result.data);
                    });
                }else if(href == '#!adList'){
                    window.location.hash = '#!adList';
                }else{
                    window.location.hash = '#!account';
                }
                http.do("/notice/updateMessage",{param:JSON.stringify({id:oid})}).then(
                    function (result) {
                        if (result.data == 1) {
                            //更新成功！
                            var num = $('#message-num').text() - 1;
                            if (num == 0) {
                                $('#message-num').hide();
                                $("#mess-m").show();
                                $("#mess-time").html("");
                            } else {
                                $('#message-num').text(num);
                            }
                        } else {
                            console.log("更新失败！返回值为：" + result.data);
                        }
                    }
                );
                $(this).closest("li").remove();
                //	$("#mess-drop").hide();
            });
            _this.addMyEventListener(afterStr, subNum);
            return lastTime;

        }
        /*
        *   加载进度
        * */
        ,LoadingSchedule: function(num, info){
            var loadPage    = document.getElementById('loadPage'),
                lpNum       = loadPage.getElementsByClassName('lp-num')[0],
                lpnSlider   = loadPage.getElementsByClassName('lpn-slider')[0],
                lpInfo      = loadPage.getElementsByClassName('lp-info')[0];
            lpnSlider.style.width = num + '%';
            lpInfo.innerHTML = info;
            if(num === 100){
                window.setTimeout(function(){
                    loadPage.remove();
                    document.getElementById('loadPageCss').remove();
                }, 500);
            }
        }

        /*
         *   建立长链接
         * */
        ,openWebSocket: function(userId){
            var _this = this;
            $.ajax({
                type: 'POST',
                url:cors_config.api_host+'/common/getConfigInfo',
                xhrFields: {
                    withCredentials: true
                },
                success: function(res){
                    var json = typeof(res) == 'string' ? JSON.parse(res) : res;
                    if(json.flag == 'fail'){
                        console.log("websocket 连接信息没有从配置中心获取到。");
                        return;
                    }
                    var data = json.data;
                    var websocket_url = data.url;
                    var websocket_time = data.heartTime;
                    //打开websocket
                    if(!websocket_url){
                        return;
                    }
                    var wsServer = websocket_url;
                    var websocket = new WebSocket(wsServer);
                    websocket.onopen = function (evnt) {
                        websocket.send("userId:" + userId);
                        //心跳测试
                        setInterval(function () {
                            websocket.send("test");
                        }, websocket_time);
                    };
                    websocket.onmessage = function (evnt) {
                        //接受数量
                        var json = JSON.parse(evnt.data);
                        if (json.flag != null) {
                            return;
                        }
                        _this.handleData(json);
                    };
                    websocket.onerror = function (evnt) {
                        console.log("websocket 异常：" + evnt.data);
                    };
                    websocket.onclose = function (evnt) {
                        console.log('Disconnecting connection');
                    };
                }
            });
        }
        /*
        * @处理消息中心数据
        * */
        ,handleData: function(json){
            var _this = this;
            var messageNum = $('#message-num'),
                messM = $("#mess-m");
            if (json.totalSize == 0) {
                //没有数据 显示空白页
                messageNum.hide();
                messM.show();
                console.log("没有消息！");
            } else {
                messageNum.text(json.totalSize);
                messageNum.data("num", json.totalSize);
                messM.hide();
                messageNum.show();
                //抖一抖
//            $("#mess-bell").effect("shake", {distance: 3, times: 8}, 100);
                var lastTime = _this.handleMessage(json);
                //Last updated on: 12/12/2013 9:43AM
                var htmlTime = I18N.getText('index', 'lastUpdate') + moment(lastTime).format("YYYY-MM-DD HH:mm:ss") + " GMT ";
                if (new Date(lastTime).getTimezoneOffset() / 60 > 0) {
                    htmlTime += "+" + new Date(lastTime).getTimezoneOffset() / 60;
                } else {
                    htmlTime += "+" + new Date(lastTime).getTimezoneOffset() / -60;
                }
                $("#mess-time").html(htmlTime);
                console.log("从服务器返回的消息为：");
                //console.log(json);
            }
        }
        ,addMyEventListener : function (afterStr, subNum) {
            var _this = this;
            $(".bell-warp .list-group").find(".mess-open").unbind("click");
    //        $("#logo-group-me").find(".mess-head-a").unbind("click");
            $(".bell-warp .list-group").find(".list-group-item").find(".badge").unbind("click");

            $(".bell-warp .list-group").find(".mess-open").bind("click", function () {
                //    toggleText(this, afterStr, subNum);
                var openStatus = this.getAttribute('open-status'),
                    forContent = $('.mess-body', $(this).closest('.list-group-item'));
                if(openStatus == 'true'){
                    forContent.removeClass('show-all');
                }else{
                    forContent.addClass('show-all');
                }
            });
            $(".bell-warp .list-group").find(".list-group-item").find(".badge").bind("click", function () {
                _this.clickTitle($(this).closest("li"));
            });
        }
        ,initMessageModal: function(da){
            var _this = this;
            var the = $("body>div.modal.common-modal");
            var box = $('<div class="row"></div>');
            console.log(da)
            for(var i =0;i<da.length;i++){
                var o = da[i];
                var app = o.appNames;//应用
                var langs = $.isArray(o.languages) ? o.languages.join(',') : '';//语言
                var gender = (o.gender==1?"男":(o.gender==2?"女":"全部"));//性别
                var txt = '<div class="col-sm-6">\
						<div class="thumbnail pull-left">\
							<img style="max-height:100px;max-width:120px" class="superbox-img" src="'+o.litImgURL+'">\
						</div>\
					<ul class="messageModal-desc">\
						<li>应用：<span title="'+(app.join(" "))+'">'+(app.join(" "))+'</span> </li>\
						<li>语言：<span >'+langs+'</span> </li>\
						<li>性别：<span>'+gender+'</span>\
						</li>\
					</ul></div>';
                box.append(txt);
            }
            the.empty().dialog({
                id:"messageModal",
                title:"图片详情",
                body:box
            }).modal();
        }
        ,clickTitle : function (obj) {
            var _this = this;
            $(obj).remove();
            var id = $(obj).attr("id");
            $.ajax( {
                type : "POST",
                url : cors_config.api_host+'/notice/updateMessage',
                data: {param:'{"id":"'+ id +'"}'},
                xhrFields: {
                    withCredentials: true
                },
                success : function(data, textStatus, xmLHttpRequest){
                    var data = data.data;  //数据格式变更，为保证原代码不变做重新赋值处理
                    if (data == 1) {
                        //更新成功！
                        var num = $('#message-num').text() - 1;
                        if (num == 0) {
                            $('#message-num').hide();
                            $("#mess-m").show();
                            $("#mess-time").html("");
                        } else {
                            $('#message-num').text(num);
                        }
                    } else {
                        console.log("更新失败！返回值为：" + data);
                    }
                }
            });
        }
    };
    return baseFn;
});
